import cv2
import numpy as np


def image_normalization(image):
    image = image/255
    return (image-0.5)/0.5


def image_denormalization(image):
    return (image*0.5+0.5)*255



def mask_merge(mask,image1,image2):
    '''
    image1 人脸风格化
    image2 整张风格化 抠出来的
    '''
    
    assert image1.shape == image2.shape,'image shape should be same'
    
    h = image1.shape[0]
    w = image1.shape[1]

    mask = cv2.resize(mask,(w,h))
    mask = np.stack([mask] * 3, axis=-1)/255
    # cv2.imwrite('result/result3.jpg',np.concatenate([image1,image2]))
    return mask*image1+(1-mask)*image2



def nms(boxes,
        scores,
        max_output_size,
        iou_threshold=0.5,
        score_threshold=float('-inf'),
        name=None):
    x1 = boxes[:,0]
    y1 = boxes[:,1]
    x2 = boxes[:,2]
    y2 = boxes[:,3]
    
    scores = scores
    
    areas = (x2 - x1) * (y2 - y1)
    order = scores.argsort()[::-1]    
    keep = []

    while order.size > 0:  # 还有数据
        i = order[0]
        keep.append(i)
        if order.size==1:break
        # 计算当前概率最大矩形框与其他矩形框的相交框的坐标
        xx1 = np.maximum(x1[i], x1[order[1:]])
        yy1 = np.maximum(y1[i], y1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])

        # 计算相交框的面积
        w = np.maximum(0.0, xx2 - xx1)
        h = np.maximum(0.0, yy2 - yy1)
        inter = w * h
        # 计算重叠度IOU：重叠面积/（面积1+面积2-重叠面积）
        IOU = inter / (areas[i] + areas[order[1:]] - inter)
     
        # 找到重叠度不高于阈值的矩形框索引
        left_index = (np.where(IOU <= iou_threshold))[0]
        
        # 将order序列更新，由于前面得到的矩形框索引要比矩形框在原order序列中的索引小1，所以要把这个1加回来
        order = order[left_index + 1]
    return keep[:max_output_size]